from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from django_redis import get_redis_connection
from goods.models import SKU
from decimal import Decimal
# Create your views here.
from orders.serializers import OrderSettlementSerializer, SaveOrderSerializer
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView

class OrderSettlementView(APIView):

    def get(self, request):
        # 建立连接
        conn = get_redis_connection('cart')
        user = request.user

        # 从缓存中获取sku_id 和count
        sku_id_count = conn.hgetall('cart_%s'%user.id)
        # 获取选中状态数据
        cart_selected = conn.smembers('cart_selected_%s'%user.id)

        # 数据构建 {}
        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)]=int(sku_id_count[sku_id])

        # 查询数据对象
        sku_list = SKU.objects.filter(id__in=cart.keys())
        # 运费
        freight = Decimal('10.00')
        # 添加属性
        for sku in sku_list:
            sku.count=cart[sku.id]

        # 序列化返回
        ser = OrderSettlementSerializer({'freight':freight, 'skus':sku_list})

        return Response(ser.data)

class SaveOrderView(CreateAPIView):
    serializer_class = SaveOrderSerializer
    permission_classes = [IsAuthenticated]

